# insert_sort.S - Insert sort function
.section .text
# void intert_sort(int *a, int n)
.globl insert_sort
	.type inster_sort, @function
insert_sort:
	pushl %edi
	pushl %esi
	pushl %ebx

	movl 16(%esp), %edi	# testdata is in %edi
	movl 20(%esp), %esi	
	dec %esi			# n - 1 is in %esi

	movl %edi, %ebx
	addl %esi, %ebx		# a + n - 1 is in %ebx

	movl %edi, %eax
	inc %eax			# a + i is in %eax

	for:
		cmpl %ebx, %eax
		ja endfor
	forcode:
		movzbl (%eax), %edx	# temp is in %dl
		movl %eax, %ecx
		dec %ecx			# a + j is in %ecx
		
		while:
			cmpl %edi, %ecx
			jb endwhile
			cmpb %dl, (%ecx)
			jle endwhile
		whilecode:
			movb (%ecx), %dh
			movb %dh, 1(%ecx)
			dec %ecx
			jmp while
		endwhile:
		
		movb %dl, 1(%ecx)
		inc %eax
		jmp for
	endfor:

	popl %ebx
	popl %esi
	popl %edi
	ret
